<template>
	<view class="content">
		<u-tabs :list="list" :is-scroll="false" :current="current" @change="change" :active-color="activeColor"
			:font-size="fontSize" :inactive-color="inactiveColor"></u-tabs>
		<view class="order-content">
			<view class="order-list">
				<view class="order-item" v-for="(item,index) in courseList" :key="index" @click="toCourseDetail(item)">
					<view class="order-header">
						<view class="">
							{{item.outTradeNo}}
						</view>
						<view class="">
							{{item.pay_status == 0?'待付款':'已完成'}}
						</view>
					</view>
					<view class="card-right-img">
						<view class="card-item">
							<view class="card-left">
								<image :src="item.course_id[0].main_pic" mode=""></image>
							</view>
							<view class="card-right">
								<view class="top">
									<text>{{item.course_id[0].name}}</text>
								</view>
								<view class="bottom">
									<view class="left">
										<text>{{item.update_time | timefilter}}</text>
									</view>
									<view class="right">
										<text>￥{{item.course_id[0].sale_price}}</text>
									</view>

								</view>
							</view>

						</view>
					</view>
					<view class="foot-button-box" v-if="item.pay_status == 0">
						<u-button size="medium" type="success" shape="circle" @click="purchase(item)">支付</u-button>
						<u-button class="second-button" size="medium" type="default" shape="circle" @click="cancel(item)">取消</u-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				current: 0,
				list: [{
					name: '全部'
				}, {
					name: '待付款'
				}, {
					name: '已完成'
				}],
				activeColor: '#04BA8F',
				fontSize: '32',
				inactiveColor: '#666666',
				courseList: []
			}
		},
		onLoad() {
			// this.getOrder(0);
		},
		onShow() {
			this.getOrder(this.current);
		},
		filters: {
			timefilter(parseTime) {
				// const parseTime = (Date.parse(time)); //转化成时间戳
				const timeStr = new Date(parseTime);
				const year = timeStr.getFullYear()
				const month = (timeStr.getMonth() + 1).toString().padStart(2, 0)
				const day = timeStr.getDate().toString().padStart(2, 0)
				const hours = timeStr.getHours().toString().padStart(2, 0);
				const minute = (timeStr.getMinutes()).toString().padStart(2, 0);
				// const second = (timeStr.getSeconds()).toString().padStart(2, 0);
				return year + '-' + month + '-' + day + ' ' + hours + ':' + minute
			}
		},
		watch: {
			current(newVal, oldVal) {
				this.getOrder(newVal);
			}
		},
		methods: {
			toCourseDetail(e){
				const courseObj = e.course_id[0];
				uni.navigateTo({
					url:'../orderDetail/orderDetail?courseId=' + courseObj._id + "&tid=" + courseObj.teacher_id + "&orderId=" + e._id
				})
			},
			change(index) {
				this.current = index;
			},
			getOrder(cur) {
				var that = this;
				that.courseList = [];
				const user_id = uni.getStorageSync('user_id');
				const db = uniCloud.database()
				db.collection('order')
					.where("user_id=='" + user_id + "'")
					.field('user_id,course_id,pay_status,outTradeNo,update_time')
					.get()
					.then(res => {
						console.log('go', res);
						if (res.result.data.length != 0) {
							if (cur == 0) {
								res.result.data.forEach((item, index) => {
									that.getCourseData(item);
								})
								console.log('quanbu', that.courseList)
							} else if (cur == 1) {
								res.result.data.forEach((item, index) => {
									if (item.pay_status == 0) {
										that.getCourseData(item);
									}
								})
							} else if (cur == 2) {
								res.result.data.forEach((item, index) => {
									if (item.pay_status == 1) {
										that.getCourseData(item);
									}
								})
							}
							return
						}
					}).catch(err => {
						console.error(err)
					})
			},
			getCourseData(cdata) {
				var that = this;
				const user_id = uni.getStorageSync('user_id');
				const db = uniCloud.database()
				db.collection('order,userinfo,opendb-mall-goods')
					.where("user_id._id=='" + user_id + "' && course_id._id=='" + cdata.course_id + "'")
					.field(
						'user_id{username},course_id{_id,body,main_pic,sale_price,name,teacher_id},pay_status,outTradeNo,update_time')
					.get()
					.then(res => {
						console.log('gcd', res);
						if (res.result.data.length != 0) {
							let courseData = res.result.data[0];
							that.courseList.push(courseData);
							return
						}
					}).catch(err => {
						console.error(err)
					})
			},
			purchase(course) {
				var that = this;
				const courseObj = course.course_id[0];
				const body = courseObj.body;
				const outTradeNo = course.outTradeNo;
				const totalFee = courseObj.sale_price * 100;
				console.log(body, outTradeNo, totalFee)
				const openid = uni.getStorageSync("openid");
				uniCloud.callFunction({
					name: 'getOrderInfo',
					data: {
						openid: openid,
						body: body,
						outTradeNo: outTradeNo,
						totalFee: totalFee,
					},
					success(res) {
						var orderInfo = res.result.orderInfo
						if (orderInfo) {
							return new Promise((resolve, reject) => {
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: orderInfo.timeStamp,
									nonceStr: orderInfo.nonceStr,
									package: orderInfo.package,
									signType: orderInfo.signType,
									paySign: orderInfo.paySign,
									success: function(res) {
										console.log('success:' + JSON.stringify(res));
										const user_id = uni.getStorageSync("user_id");
										const db = uniCloud.database()
										db.collection('order')
											.where("user_id =='" + user_id +
												"' && course_id=='" + courseObj._id +
												"' && pay_status == 0")
											.update({
												pay_status: 1
											})
											.then(res => {
												console.log('upo', res);
												if (res.result.updated == 1) {
													uni.showToast({
														title: '支付成功',
														icon: "none"
													})
													that.getOrder(that.current);
												}
											}).catch(err => {
												console.error(err)
												uni.showToast({
													title: '支付失败',
													icon: "none"
												})
											})
									},
									fail: function(err) {
										console.log('fail:' + JSON.stringify(err));
										
										uni.showToast({
											title: '支付失败',
											icon: "none"
										})
									}
								});
							})
						}
					},
					fail(res) {
						console.log(res)
					}
				})
			},
			cancel(course){
				var that = this;
				const db = uniCloud.database();
				db.collection("order").where("_id=='"+ course._id + "'").remove().then(res=>{
					console.log('cr',res)
					if(res.result.deleted == 1){
						uni.showToast({
							title:'订单已取消',
							icon:'none'
						})
						that.getOrder(that.current);
						return
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FAFAFA;
	}

	.content {
		background-color: #FAFAFA;
	}

	.order-content {
		.order-list {
			.order-item {
				background-color: #fff;
				width: 680rpx;
				padding: 20rpx 15rpx;
				margin: 0 auto;
				margin-top: 20rpx;
				border-radius: 10rpx;

				.order-header {
					display: flex;
					flex-wrap: wrap;
					justify-content: space-between;
					font-size: 26rpx;
					color: #333333;
					padding-bottom: 20rpx;
				}
			}
		}
	}

	//图片在左侧的 card-right-img
	.card-right-img-wrap {
		background-color: #F4F5F9;
		// padding: 15rpx;
	}

	.card-right-img {
		background-color: #fff;
		// padding: 0 15rpx;

		.card-item {
			display: flex;
			flex-wrap: wrap;
			// justify-content: space-between;
			padding: 20rpx 0;
			border-top: 1px solid #FAFAFA;

			.card-left {
				width: 260rpx;
				height: 140rpx;
				border-radius: 10rpx;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.card-right {
				display: flex;
				flex-direction: column;
				flex-wrap: wrap;
				justify-content: space-between;
				padding: 20rpx 0 10rpx 0;
				width: 370rpx;
				margin-left: 30rpx;

				.top {
					font-size: 28rpx;
					color: #434343;
					// font-weight: bold;
				}

				.bottom {
					display: flex;
					flex-direction: row;
					justify-content: space-between;

					.left {
						color: #B5B5B5;
						font-size: 24rpx;
					}

					.right {
						color: #F56C6C;
						font-size: 28rpx;
						font-weight: bold;
					}
				}
			}
		}
	}

	.foot-button-box {
		border-top: 1px solid #FAFAFA;
		padding-top: 20rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-end;

		.second-button {
			margin-left: 20rpx;
		}
	}
</style>
